package com.gogo.mall.utils;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.*;
import com.aliyun.teaopenapi.models.*;
import com.aliyuncs.exceptions.ClientException;

public class Sms {
    /**
     * 使用AK&SK初始化账号Client
     * @param accessKeyId
     * @param accessKeySecret
     * @return Client
     * @throws Exception
     */
    public static Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
        Config config = new Config()
                // 您的AccessKey ID
                .setAccessKeyId(accessKeyId)
                // 您的AccessKey Secret
                .setAccessKeySecret(accessKeySecret);
        // 访问的域名
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new com.aliyun.dysmsapi20170525.Client(config);
    }

    /**
     * 6位随机数生成
     * @return
     */
    public static String randomNum (){
        Integer code = (int)((Math.random()*9+1)*100000);
        return code.toString();
    }
    public static String sendSms(String tel) throws Exception {
        com.aliyun.dysmsapi20170525.Client client = Sms.createClient("LTAI4G7KWNAKJ5EPBDMCfx9J", "3c92CRJABcB6KOsd6eilLTMxHoJ84y");
        String code = randomNum();
        try {
            SendSmsRequest sendSmsRequest = new SendSmsRequest()
                    .setPhoneNumbers(tel)
                    .setSignName("javastudy")
                    .setTemplateCode("SMS_204277173")
                    .setTemplateParam("{\"code\":"+code+"}");
            SendSmsResponse sendSmsResponse = client.sendSms(sendSmsRequest);
            String flag = sendSmsResponse.getBody().getCode();
            if(flag.equals("OK"))
                return code;
            return null;
        }catch (ClientException e) {
            throw new ClientException("验证码发送失败！");
        }
    }
}
